// @ts-nocheck
import { RouteLocationNormalized, RouteRecordRaw } from 'vue-router';
import { useUserStore } from '@/store';

export default function usePermission() {
  const userStore = useUserStore();
  return {
    //所有的权限
    accessRouter(route: RouteLocationNormalized | RouteRecordRaw) {
      return (
        !route.meta?.requiresAuth
        || !route.meta?.roles
        || route.meta?.roles?.includes('*')
        || route.meta?.roles?.includes(userStore.role)
        || this.permissionRouter(route)
          // (
          //   !route.meta?.requiresAuth
          //   || !route.meta?.roles
          //   || route.meta?.roles?.includes('*')
          //   || route.meta?.roles?.includes(userStore.role)
          // )
          // && this.permissionRouter(route)
      )
    },
    //权限控制下的第一个菜单路由
    findFirstPermissionRoute(_routers: any, role = 'admin') {
      const cloneRouters = [..._routers];
      while (cloneRouters.length) {
        const firstElement = cloneRouters.shift();
        if (
            this.permissionRouter(firstElement) && !firstElement?.children//leaf node
        )
          return { name: firstElement.name };
        if (firstElement?.children) {
          cloneRouters.push(...firstElement.children);
        }
      }
      return null;
    },
    // 通过所有子项路由查找当前第一个权限具备的路由
    btnFindRoute(routes: any) {
      const cloneRouters = [...routes];
      let res = ""
      while (cloneRouters.length) {
        const firstElement = cloneRouters.shift();
        if (this.permissionRouter(firstElement)) {
          res = firstElement.name;
          break
        }
      }
      return res;
    },
    //过滤菜单权限，服务端数据控制
    permissionRouter(route: RouteLocationNormalized | RouteRecordRaw){
      return userStore.permCodes.includes(route.meta?.permCode)
    },
    getPermissionCodeByName(routes: any[], name: LocationQueryValue | LocationQueryValue[]) {
      return routes.find(item => item.name === name)
      // while (routes.length) {
      //   const currentRoute = routes.shift()
      //   if (currentRoute.name === name) {
      //     return currentRoute
      //   }
      // }
    }
    // You can add any rules you want
  };
}
